package com.byedu.jupiter.util;

import java.io.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.*;

/**
 * Created by jason on 2017/6/4.
 */
public class ZipUtil {

    private static Logger logger = LoggerFactory.getLogger(ZipUtil.class);
    /**
     * 功能：解压 zip 文件，只能解压 zip 文件
     *
     * @param file
     * @param destDir
     */

    public static void unzip(File file, String destDir, String charset) {
        destDir = destDir.endsWith("\\") ? destDir : destDir + "\\";
        byte b[] = new byte[1024];
        int length;
        ZipFile zipFile = null;
        try {
            zipFile = new ZipFile(file, Charset.forName(charset));
            Enumeration enumeration = zipFile.entries();
            ZipEntry zipEntry = null;
            while (enumeration.hasMoreElements()) {
                zipEntry = (ZipEntry) enumeration.nextElement();
                File loadFile = new File(destDir + zipEntry.getName());
                if (zipEntry.isDirectory()) {
                    loadFile.mkdirs();
                } else {
                    if (!loadFile.getParentFile().exists()) {
                        loadFile.getParentFile().mkdirs();
                    }

                    OutputStream outputStream = new FileOutputStream(loadFile);
                    InputStream inputStream = zipFile.getInputStream(zipEntry);

                    while ((length = inputStream.read(b)) > 0) {
                        outputStream.write(b, 0, length);
                    }

                    outputStream.flush();
                    inputStream.close();
                    outputStream.close();
                }
            }
        } catch (IOException e) {
            logger.info("解压文件出错", e);
        }
    }
}
